﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AchievementSceneManager : LTEventListenerC {
    public UILabel pointLabel;

    public GameObject listGridObject;

	// Use this for initialization
	void Start () {
        SetActiveHelpButton(false);
#if UNITY_EDITOR
        if (UserData.Instance.userModel != null)
            NetworkManager.Instance.C2S_GET_ACHIEVEMENT_LIST(ResponseGetAchievementList, 4);
        else
        {
            ResourceManager.Inst.PatchDataFile(() =>
            {
                GameData.Init();
                //TextData.Init();
                EventData.Init();
                CashData.Init();
                //UserData.Instance.m_Language = Language.text_ko;
            });

            NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "kth18", string.Empty, ResponseLogin, null);
        }
#else
        NetworkManager.Instance.C2S_GET_ACHIEVEMENT_LIST(ResponseGetAchievementList, 4);
#endif
    }
	
	// Update is called once per frame
	void Update () {
	
	}

    private void ResponseLogin(ResponseModel<UserModel> result)
    {
        NetworkManager.Instance.C2S_GET_ACHIEVEMENT_LIST(ResponseGetAchievementList, 4);
    } 

    List<Achievement> achievementList = new List<Achievement>();
    private void ResponseGetAchievementList(ResponseModel<List<Achievement>> result)
    {
        achievementList = result.data;
        pointLabel.text = result.achievePoint.ToString();
        pointLabel.gameObject.SetActive(true);

        SetAchievementListInfos();
    }   

    List<AchievementListCell> cellList = new List<AchievementListCell>();
    float[] firstSliderColor = new float[3] { 0f, 162f, 215f };
    float[] lastSliderColor = new float[3] { 0f, 244f, 241f };
    public void SetAchievementListInfos()
    {
        int count = 0;
        float cellYPos = 0f;

        achievementList.Sort(compareAchievementState);
        for(int i=0; i<achievementList.Count; i++)
        {
            Achievement achievement = achievementList[i];
            DAchievementInfo info = GameData.Inst.GetAchievementInfo(achievement.id);
            GameObject obj = Resources.Load("Prefab/Achiev/Cell_Achievement") as GameObject;
		    AchievementListCell cell = (Instantiate(obj) as GameObject).GetComponent<AchievementListCell>();
            cell.transform.parent = listGridObject.transform;
            cell.transform.localScale = Vector3.one;
            cell.rewardButtonObject[2].GetComponent<LTButtonMessage>().m_MethodDeliver[0].m_EventListener = this;
            cell.rewardButtonObject[2].GetComponent<LTButtonMessage>().m_MethodDeliver[0].m_EventId = count;
            cell.foldUpButtonObject.GetComponent<LTButtonMessage>().m_MethodDeliver[0].m_EventListener = this;
            cell.foldUpButtonObject.GetComponent<LTButtonMessage>().m_MethodDeliver[0].m_EventId = 100000 + count;
            cell.foldDownButtonObject.GetComponent<LTButtonMessage>().m_MethodDeliver[0].m_EventListener = this;
            cell.foldDownButtonObject.GetComponent<LTButtonMessage>().m_MethodDeliver[0].m_EventId = 200000 + count++;
            cell.image.spriteName = "Ach_icon_0" + Random.Range(1,3);
            cell.achievementInfo = achievement;
            foreach (UILabel label in cell.point)
            {
                label.text = info.reward1Value1.ToString();
            }
            if (achievement.state == 1)
            {
                cell.transform.localPosition = new Vector3(0f, cellYPos, 0f);
                cell.title[0].text = TextController.GetStringWithId(string.Format("achievetitle{0}", achievement.id)).Replace("{0}", info.value1.ToString());
                cell.body.text = TextController.GetStringWithId(string.Format("achieve{0}", achievement.id)).Replace("{0}", info.value1.ToString());
                cell.count.text = string.Format("{0}/{1}", achievement.value, info.value1);
                cell.countSlider.value = achievement.value / (float)info.value1;
                float[] sliderColor = new float[3];
                for(int k=0; k<3; k++)
                {
                    sliderColor[k] = firstSliderColor[k]+((lastSliderColor[k]-firstSliderColor[k])*cell.countSlider.value);
                }
                cell.countSlider.transform.FindChild("Ach_Graph_on").GetComponent<UISprite>().color = new Color(sliderColor[0] / 255f, sliderColor[1] / 255f, sliderColor[2] / 255f);
                if (cell.countSlider.value == 0)
                    cell.countSlider.alpha = 0f;
                foreach (UILabel label in cell.rewardAmountLabel)
                    label.text = info.reward2Value1.ToString();
                if (info.reward2Type != 0)
                    cell.rewardButtonObject[1].SetActive(true);
                else
                    cell.rewardButtonObject[0].SetActive(true);
                cell.foldUpButtonObject.SetActive(false);
                cell.foldDownButtonObject.SetActive(false);
                cell.image.color = new Color(150f/255f, 150f/255f, 150f/255f);
                cellYPos -= 460f;
            }
            if (achievement.state == 2)
            {
                cell.transform.localPosition = new Vector3(0f, cellYPos, 0f);
                cell.title[0].text = string.Format("[ff0000]{0} |[-] {1}", TextController.GetStringWithId("uiAchievecomplete"), TextController.GetStringWithId(string.Format("achievetitle{0}", achievement.id)).Replace("{0}", info.value1.ToString()));
                cell.body.text = TextController.GetStringWithId(string.Format("achieve{0}", achievement.id)).Replace("{0}", info.value1.ToString());
                cell.count.text = string.Format("{0}/{1}", info.value1, info.value1);
                cell.countSlider.value = achievement.value / (float)info.value1;
                cell.countSlider.transform.FindChild("Ach_Graph_on").GetComponent<UISprite>().color = new Color(177f / 255f, 255f / 255f, 255f / 255f);
                cell.countSlider.GetComponent<Animation>().Play("Ach_Graph");
                if (cell.countSlider.value == 0)
                    cell.countSlider.alpha = 0f;
                foreach (UILabel label in cell.rewardAmountLabel)
                    label.text = info.reward2Value1.ToString();
                if (info.reward2Type != 0)
                    cell.rewardButtonObject[2].SetActive(true);
                else
                    cell.rewardButtonObject[0].SetActive(true);
                cell.completeAchievementBGObject.SetActive(true);
                cell.foldUpButtonObject.SetActive(false);
                cell.foldDownButtonObject.SetActive(false);
                cellYPos -= 460f;
            }
            if (achievement.state == 3)
            {
                cell.transform.localPosition = new Vector3(0f, cellYPos, 0f);
                cell.title[0].text = string.Format("[ff0000]{0} |[-] {1}", TextController.GetStringWithId("uiAchievecomplete"), TextController.GetStringWithId(string.Format("achievetitle{0}", achievement.id)).Replace("{0}", info.value1.ToString()));
                cell.title[1].text = string.Format("[ff0000]{0} |[-] {1}", TextController.GetStringWithId("uiAchievecomplete"), TextController.GetStringWithId(string.Format("achievetitle{0}", achievement.id)).Replace("{0}", info.value1.ToString()));
                cell.body.text = TextController.GetStringWithId(string.Format("achieve{0}", achievement.id)).Replace("{0}", info.value1.ToString());
                cell.count.text = string.Format("{0}/{1}", info.value1, info.value1);
                cell.countSlider.value = achievement.value / (float)info.value1;
                cell.countSlider.transform.FindChild("Ach_Graph_on").GetComponent<UISprite>().color = new Color(11f / 255f, 107f / 255f, 138f / 255f);
                foreach (UILabel label in cell.rewardAmountLabel)
                    label.text = info.reward2Value1.ToString();
                if (info.reward2Type == 0)
                    cell.rewardButtonObject[4].SetActive(true);
                else
                    cell.rewardButtonObject[3].SetActive(true);
                cell.ingAchievementCellObject.SetActive(false);
                cell.completedAchievementCellObject.SetActive(true);
                cell.completeAchievementBGObject.SetActive(true);
                cell.foldUpButtonObject.SetActive(true);
                cell.foldDownButtonObject.SetActive(true);
                cellYPos -= 230f;
            }
            cellList.Add(cell);
        }
    }

    public int compareAchievementState(Achievement a, Achievement b)
    {
        int stateA = a.state;
        int stateB = b.state;

        if (stateA == 3)
            stateA = 1;
        if (stateB == 3)
            stateB = 1;

        if (stateA > stateB)
            return -1;
        else if (stateA < stateB)
            return 1;

        return 0;
    }

    int rewardedIndex = 0;
    public override void OnEvent(int eventID)
    {
        Debug.LogError("OnEvent - "+eventID);
        base.OnEvent(eventID);

        if (eventID == 10001)
        {

        }
        else if (eventID == 10002)
        {

        }
        else if (eventID == 10003)
        {

        }
        else if (eventID == 10004)
        {

        }
        else if (eventID == 10005)
        {

        }
        else if (eventID >= 100000 && eventID < 200000)
        {
            FoldUpCell(eventID - 100000);
        }
        else if( eventID >= 200000 )
        {
            FoldDownCell(eventID - 200000);
        }
        else
        {
            rewardedIndex = eventID;
            GetAchievementReward(eventID);
        }
    }

    public void GetAchievementReward(int index)
    {
        NetworkManager.Instance.C2S_GET_ACHIEVEMENT_REWARD(ResponseGetAchievementReward, achievementList[index].id);
    }

    private void ResponseGetAchievementReward(ResponseModel<UserModel> result)
    {
        UserData.Instance.userModel = result.data;
        cellList[rewardedIndex].rewardButtonObject[2].SetActive(false);
        cellList[rewardedIndex].rewardButtonObject[3].SetActive(true);

        DAchievementInfo info = GameData.Inst.GetAchievementInfo(achievementList[rewardedIndex].id);
        pointLabel.text = (int.Parse(pointLabel.text) + info.reward1Value1).ToString();

        SceneController.m_TopLeftMenu.GetComponent<Panel_TopLeft>().UpdateUI();
    }

    public void FoldUpCell(int index)
    {
        cellList[index].completedAchievementCellObject.SetActive(true);
        cellList[index].ingAchievementCellObject.SetActive(false);

        for (int i = index+1; i < cellList.Count; i++)
        {
            Vector3 pos = cellList[i].transform.localPosition;
            pos.y += 230f;
            cellList[i].transform.localPosition = pos;
        }
    }

    public void FoldDownCell(int index)
    {
        cellList[index].completedAchievementCellObject.SetActive(false);
        cellList[index].ingAchievementCellObject.SetActive(true);
        cellList[index].foldUpButtonObject.SetActive(true);

        for (int i = index+1; i < cellList.Count; i++)
        {
            Vector3 pos = cellList[i].transform.localPosition;
            pos.y -= 230f;
            cellList[i].transform.localPosition = pos;
        }
    }

    public override void BackButton()
    {
        CheckCompleteAchievements();
    }

    public override void HomeButton()
    {
        CheckCompleteAchievements();
    }

    void CheckCompleteAchievements()
    {
        foreach(Achievement achievememt in achievementList)
        {
            DAchievementInfo info = GameData.Inst.GetAchievementInfo(achievememt.id);
            if( achievememt.state == 2 && info.reward2Type == 0 )
            {
                SendToServerCompleteAchievement(achievememt.id);
            }
        }

        base.HomeButton();
    }

    void SendToServerCompleteAchievement(int achievementId)
    {
        NetworkManager.Instance.C2S_GET_ACHIEVEMENT_REWARD((result) => {           
        }, achievementId);
    }
}
